'use strict';

import React from 'react';

import {
    HttpService,
    Toast
} from '../utils'
// import {HttpService, Toast}  from'../Http';

import phone from '../img/login/phone.png'
import pwd from '../img/login/pwd.png'
import user from '../img/login/user.png'

import Model from './common/model'

import header from '../img/login/header.jpg'
import footer from '../img/login/footer.jpg'

import {
    connect
} from 'react-redux';
import {
    bindActionCreators
} from 'redux';

//import {Router, Route, IndexRoute, browserHistory} from 'react-router';

import Link from './common/Link'
import WxServer from '../wx/WxServer'

import {
    doLogin2
} from '../action/index'
import {
    urlKey
} from '../Tool'

class Login extends React.Component {
    static contextTypes = {
        router: React.PropTypes.object.isRequired
    };

    constructor(props) {
        super(props);
        this.state = {
            model: {},
            banners: {},
            flag: false,
            wxlogincbFlag: false,
            openid: '',
            wxgo: true,
            way: 0,
            timer: 119,
            text: '获取验证码',
            disabled: false
        };
        this.modelConfig = {
            header: <div className="header">

                <img src={header} className="app-all-img"/>

            </div>,
            content: <div className="content">
                <div className="_header">
                    市民认证
                </div>
                <div className="_content">
                    姓名和身份证不匹配，身份证姓名和身份证不匹配，身份证姓名和身份证不匹配，身份证姓名和身份证不匹配，身份证
                </div>
                <div className="_footer">
                    去认证
                </div>
            </div>,
            footer: <div className="footer">
                    <img src={footer} className="app-all-img"/>
                </div>

        }
    }

    componentWillMount() {
        //退出登录——教师返回
        if (this.props.params.from == 'jxt') {
            localStorage.logout = 1;
            if (/micromessenger/.test(navigator.userAgent.toLowerCase())) {
                HttpService.query({
                    url: '/teacherapp/teacher/unassociateWithWeChat',
                    data: {
                        token: this.props.params.token,
                        weixinclient: 'true'
                    },
                    success: (res => {
                        console.log(res);
                    })
                });
            }
            console.log('loginauto');
        }
        this.setState({
            openid: localStorage.openid
        });
        if (localStorage.logout == 1) {
            this.setState({
                wxgo: false
            })
        }
        const appdown = localStorage.appdown;
        localStorage.clear();
        sessionStorage.clear();
        if (urlKey('newlink') != '') {
            localStorage.newlink = urlKey('newlink')
        }
        localStorage.appdown = appdown;
        let state = urlKey('state');
        if (state == 'teacher') {
            if (!urlKey('code'))
                document.title = '随寻通教师端';
            localStorage.teacher = 1;
        } else {
            state = 'guardian';
        }
        if (/micromessenger/.test(navigator.userAgent.toLowerCase()) && location.host.indexOf('wx.17find.com') > -1) {
            if (this.props.params.from == 'jxt')
                return
            if (urlKey('code')) {
                this.a();
            } else {
                let gotolink = 'http://wx.17find.com/'
                if (urlKey('newlink') != '')
                    gotolink += '?newlink=pay'
                location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?' +
                    'appid=wx85577a457cfcd222&redirect_uri=' + encodeURIComponent(gotolink) + '&response_type=code&scope=snsapi_userinfo&state=' + state + '#wechat_redirect'
            }
        } else {
            this.setState({
                wxgo: false
            })
        }
    }
    componentDidMount() {
        // this.refs.phone.value = 13678419967
        // this.refs.pwd.value = 123456
        // WxServer.init();
        setTimeout(() => {
            this.setState({
                wxgo: false
            })
        }, 6000)
    }

    componentWillUnmount() {
        let loginStr = '登录'
        if (localStorage.teacher == 1)
            loginStr = '登录-教师端'
        if (_hmt)
            _hmt.push(['_trackEvent', 'page', 'login', loginStr])
        console.log(loginStr);
    }

    a() {
        if (!this.props.params.type) {
            setTimeout(() => {
                if (localStorage.teacher != 1)
                    WxServer.init()
            }, 0);
            setTimeout(async() => {
                let sondData = {
                    code: urlKey('code'),
                    state: 'guardian'
                };
                if (localStorage.teacher == 1)
                    sondData.state = 'teather';
                //授权登陆
                const result = await HttpService.query({
                    url: '/thirdparty/weixin/wxlogin_callback',
                    data: sondData
                });
                this.setState({
                    openid: result.data.openid
                });
                localStorage.openid = result.data.openid;
                if (result.data.account)
                    localStorage.userphone = result.data.account
                if (result.code == 50006) { //未绑定微信需要跳到登录页并传openid
                    this.setState({
                        wxgo: false
                    })
                    return;
                } else if (result.code == 10008) { //返回token直接跳转首页
                    if (localStorage.teacher == 1) { //教师端
                        localStorage.appToken = result.data.token;
                        if (result.data.type == 3 || !result.data.type) {
                            Toast.toast('该账户未开通教师权限，请联系客服！')
                            this.setState({
                                wxgo: false
                            })
                        } else {
                            this.context.router.push(`/teacher/${result.data.type}`);
                        }
                        return;
                    }

                    this.props.doLogin2(result.data.token, result.data.userid);
                    this.context.router.push('/map/' + result.data.token + '/' + result.data.userid);
                    localStorage.appToken = result.data.token;
                    localStorage.userid = result.data.userid;
                    return;
                } else if (result.code == 100072) { //如果账号不存在跳转到注册页并传openid
                    localStorage.notclean = 1;
                    this.context.router.push('/register');
                    return;
                } else if (result.code == 100073) { //未扫描设备，跳到添加设备页
                    if (result.data.account) {
                        localStorage.userphone = result.data.account
                        localStorage.userid = result.data.userid;
                        localStorage.notclean = 1;
                        localStorage.appToken = result.data.token
                        this.context.router.push('/AddDevice');
                    } else {
                        this.setState({
                            wxgo: false
                        })
                        Toast.toast('未获取到登录手机号，重新登录')
                        return;
                    }
                }
                this.setState({
                    wxgo: false
                })
                Toast.toast(result.msg)
            }, 1);
        }
    }

    async login() {
        const phone = this.refs.phone.value;
        const pwd = this.refs.pwd.value;
        const way = this.state.way;
        if (phone == '') {
            Toast.toast('请输入手机号');
            return;
        } else if (!/^1[34578]\d{9}$/.test(phone)) {
            Toast.toast('手机格式不正确');
            return;
        }
        if (!pwd) {
            Toast.toast(`请输入${way==0?'密码':'验证码'}`);
            return;
        }
        localStorage.delDevice = 0;
        localStorage.userphone = phone;

        let loginUrl = '/app/user/login'
        if (localStorage.teacher == 1)
            loginUrl = '/teacherapp/teacher/loginnew' //'/teacherapp/teacher/login'
        let data = {
            account: phone,
            password: pwd,
            weixinclient: 'true',
            openid: this.state.openid
        }
        if (way == 1) { //短信登录
            loginUrl = '/app/user/loginsms'
            if (localStorage.teacher == 1)
                loginUrl = '/teacherapp/teacher/loginsms' //'/teacherapp/teacher/login'
            data.smscode = pwd
        } else {
            data.password = pwd
        }
        var result = await HttpService.query({
            url: loginUrl,
            data
        });
        if (result.code == 10008) {
            this.props.doLogin2(result.data.token, result.data.userid);
            this.context.router.push('/map/' + result.data.token + '/' + result.data.userid);
            localStorage.appToken = result.data.token;
            localStorage.userid = result.data.userid;
            return;
        } else if (result.code == 100073) {
            localStorage.userid = result.data.userid;
            localStorage.appToken = result.data.token
            this.context.router.push('/AddDevice');
            return;
        } else if (result.code == 20002) { //教师端
            localStorage.appToken = result.data.token;
            if (result.data.type == 3) {
                Toast.toast('该账户未开通教师权限，请联系客服！')
            } else {
                this.context.router.push(`/teacher/${result.data.type}`);
            }
            return;
        }
        Toast.toast(result.msg)
    }

    //登录方式切换
    loginWay(way) {
        this.setState({
            way
        })
        this.refs.pwd.value = '';
    }

    //发送验证码
    async sendCode() {
        let {
            timer,
            disabled
        } = this.state;
        if (disabled)
            return
        const phone = this.refs.phone.value;
        if (phone == '') {
            Toast.toast('请输入手机号');
            return;
        } else if (!/^1[34578]\d{9}$/.test(phone)) {
            Toast.toast('手机格式不正确');
            return;
        }
        let code = await HttpService.save({
            url: "/app/user/checkTelephone",
            data: {
                account: phone,
                weixinclient: true
            }
        });
        if (code.code != 10002) {
            if (code.msg == '手机号可以注册')
                code.msg = '手机号未注册'
            Toast.toast(code.msg)
            return
        }
        var result = await HttpService.query({
            url: '/app/user/generateSMSCode',
            data: {
                account: phone,
                module: 'loginsms'
            }
        });
        if (result.code == 10004) {
            sessionStorage.sendCode = 1
            this.setState({
                disabled: true,
                text: timer + '秒后重发'
            });
            this.countdown = setInterval(() => {
                --timer;
                if (timer <= 0) {
                    this.setState({
                        disabled: false,
                        text: '获取验证码',
                        timer: 119
                    });
                    clearInterval(this.countdown);
                    return;
                }
                this.setState({
                    disabled: true,
                    text: timer + '秒后重发',
                    timer
                })
            }, 1000);
        } else {
            Toast.toast(result.msg)
        }
    }
    render() {
        const {
            model,
            flag,
            wxgo,
            way,
            text,
            disabled
        } = this.state;
        return (
            <div>
                {wxgo == true
                    ? <div className='loadwx'></div>
                    : <div>
                        {flag == false
                            ? <div className="app-login app-padding-lr24" ref='_login'>
                                    <Model modelConfig={this.modelConfig} flag={model.flag}/>
                                    <div className="step">
                                        <div className="s-center">
                                            <div className="login-img">
                                                <img src={user} className="app-wh100-all"/>
                                            </div>
                                        </div>
                                    </div>
                                    <div className='loginwaybar'>
                                        <label onClick={this.loginWay.bind(this,0)} className={way==0?'active':null}>密码登录</label>
                                        <label onClick={this.loginWay.bind(this,1)} className={way==1?'active':null}>验证码登录</label>
                                    </div>
                                    <div className="step border-bottom app-wh120 relative">
                                        <div className="app-wh-45 app-margin-right24">
                                            <img className="app-wh100-all-radius" src={phone}/>
                                        </div>
                                        <div className="s-flex1 app-666-font30">
                                            <input className="app-333-font28 login-input" maxLength='11' placeholder='手机号' type="tel" ref='phone'/>
                                        </div>
                                        {way==1?
                                            <input type='button' value={text} className={disabled?'loginbtncode lbc_disabled':'loginbtncode'} onClick={this.sendCode.bind(this)} />
                                            :null
                                        }
                                    </div>
                                    <div className="step border-bottom app-wh120">
                                        <div className="app-wh-45 app-margin-right24">
                                            <img className="app-wh100-all-radius" src={pwd}/>
                                        </div>
                                        <div className="s-flex1 app-666-font30">
                                            <input className="app-333-font28 login-input" placeholder={way==0?'6-20位字符密码，区分大小写':'手机验证码'} type="password" ref="pwd"/>
                                        </div>
                                    </div>
                                    <div className="step app-yellow-radius-check-button login-btn" onClick={this.login.bind(this)}>
                                        <div className="s-center">登录</div>
                                    </div>
                                    <div className="step">
                                        <Link to={'/register'} className="s-flex1 app-a">
                                            <div className="s-flex1 s-j-end app-333-font28">新用户开通</div>
                                        </Link>
                                        <div className="app-padding-lr50 app-with1" style={{marginTop: '.2rem'}}></div>
                                        <Link to={'/ForgetPwd'} className="s-flex1 app-a">
                                            <div className="s-flex1 app-333-font28">忘记密码</div>
                                        </Link>
                                    </div>
                                </div>
                            : ''
}
                    </div>}
            </div>
        )
    }
}

const mapStateToProps = state => {
    return {};
};
const mapDispatchToProps = (dispatch) => {
    return bindActionCreators({
        doLogin2: doLogin2
    }, dispatch);
};
export default connect(mapStateToProps, mapDispatchToProps)(Login);
